﻿if(!Array.prototype.Add)
{
    Array.prototype.Add = function(obj)
    {
        this.push(obj);
    };
}

if(!Array.prototype.Remove)
{
    Array.prototype.Remove = function(obj)
    {
        for(var i = 0; i < this.length; i++)
        {
            if(this[i] == obj)
            {
                this.splice(i, 1);
                return;
            }
        }
    };
}

if(!Array.prototype.Clear)
{
    Array.prototype.Clear = function()
    {
        this.length = 0;
    };
}

if(!Array.prototype.CallForEach)
{
    Array.prototype.CallForEach = function(delegate)
    {
        for(var i = 0; i < this.length; i++) { delegate(this[i]); }
    };
}

if(!Array.prototype.CallForEachReturnWhenNotNull)
{
    Array.prototype.CallForEachReturnWhenNotNull = function(delegate)
    {
        var testValue;
        for(var i = 0; i < this.length; i++) { if(testValue = delegate(this[i])) return testValue; }
        return null;
    };
}

if(!Array.prototype.AddRange)
{
    Array.prototype.AddRange = function(values)
    {
        var thisInstance = this;
        values.CallForEach(function(value){thisInstance.Add(value);});
    };
}

if(!String.Format)
{
    String.Format = function(formatString)
    {
        for(var i = 1; i < arguments.length; i++)
         {
              formatString = String.Replace(formatString,"\\{" + (i - 1) + "}", arguments[i]);
         }
         return formatString;
    };
}

if(!String.Replace)
{
    String.Replace = function(source, find, replace)
    {
        return source.replace(new RegExp(find, "g"), replace);
    };
}

var JSTreeView_continuousImages = new String("");
var JSTreeView_DraggableNodes = new Array();

var defaultTreeImages = new Array("cbns", "cbs", "g01", "g10", "g11", "m10", "m11", "p10", "p11", "w");

function CTreeView()
{
	// internal
	this.nodeKeys = new Array();
	this.nodeObjects = new Array();
	this.nodeCollections = new Array();
	// properties
	this.isInRunTimeMode = false;
	this.name = new String("");
	this.imageList = null;
	this.Nodes = new CTreeViewNodes(this);
	this.containerElementID = "";
	this.defaultImageFolder = new String("");
	this.selectedNode = null;
	this.checkBoxes = false;
	this.checkAffectsChildren = true;
	// methods
	/* this.XML = CTreeView_XML; */
	this.HTML = CTreeView_HTML;
	this.Item = CTreeView_Item;
	this.Exists = CTreeView_Exists;
	this.Add = CTreeView_Add;
	this.Remove = CTreeView_Remove;
	this.Refresh = CTreeView_Refresh;
	this.DragDropManager = null;
	this.BeforeNodeExpand = null;
	this.BeforeNodeCollapse = null;
	this.NodeClick = null;
}

function CTreeViewNodes(treeView)
{
	// internal
	this.l_nodes = new Array();
	// properties
	this.treeView = treeView;
	// methods
	this.Add = CTreeViewNodes_Add;
	this.Clear = CTreeViewNodes_Clear;
	this.Count = CTreeViewNodes_Count;
}

function CTreeNode(nodeKey, nodeText, nodeData, nodeImageIndex, treeView, isDraggable)
{
	// internal
	this.isExpanded = false;
	this.treeView = treeView;
	// properties
	this.key = new String(nodeKey);
	this.text = new String(nodeText);
	this.data = nodeData;
	this.imageIndex = nodeImageIndex;
	this.Nodes = new CTreeViewNodes(treeView);
	this.nextSibling = null;
	this.previousSibling = null;
	this.isChecked = false;
	// methods
	this.Expand = CTreeNode_Expand;
	this.Collapse = CTreeNode_Collapse;
	this.Click = CTreeNode_Click;
	this.IsDraggable = isDraggable;
}

function CImageList()
{
	// properties
	this.Images = new Array();
	// methods
	this.Add = CImageList_Add;
}

/*****************************************************************************
*                            CTreeView Procedures                            *
******************************************************************************/
function CTreeView_CreateNodeHTML(node, depth, imageList)
{
	var HTML = new String("<tr><td class=\"treeTD\"><table width=\"100%\" cellpadding=0 cellspacing=0><tr>");
	var imageURL = new String("");
	var defaultImageFolder = node.treeView.defaultImageFolder;
	if(node.Nodes.Count()>0)
	{
		if(node.isExpanded)
		{
			if(node.nextSibling!=null) imageURL = "m11.gif"; else imageURL = "m10.gif";
		}
		else
		{
			if(node.nextSibling!=null) imageURL = "p11.gif"; else imageURL = "p10.gif";
		}
	}
	else
	{
		if(node.nextSibling!=null) imageURL = "g11.gif"; else imageURL = "g10.gif";
	}

	for(var i=0;i<depth;i++)
	{
		if(JSTreeView_continuousImages.substr(i,1) == "I")
			HTML += "<td class=\"treeTD\" style=\"width:19px\"><img src=\"" + defaultImageFolder + "/g01.gif\"></td>";
		else
			HTML += "<td class=\"treeTD\" style=\"width:19px\"><img src=\"" + defaultImageFolder + "/w.gif\"></td>";
	}
	HTML += "<td class=\"treeTD\" style=\"width:19px;\"><img class=\"treeIMG\" onclick=\"javascript:CTreeView_SwitchStatus(" + node.treeView.name + ",'" + node.key + "');\" src=\"" + defaultImageFolder + "/" + imageURL + "\" border=0></td>";
	if(node.treeView.checkBoxes)
	{
		var chkImage = "";
		if(node.isChecked)
			chkImage = "cbs.gif";
		else
			chkImage = "cbns.gif";
		HTML += "<td class=\"treeTD\" style=\"width:14px;\"><img onclick=\"javascript:CTreeView_SwitchCheckStatus(" + node.treeView.name + ",'" + node.key + "');\" id=\"CHK_" + node.treeView.name + "_" + node.key + "\" class=\"treeIMG\" src=\"" + defaultImageFolder + "/" + chkImage + "\"></td>";
	}
	HTML += "<td class=\"treeTD\" style=\"width:19px;\"><img class=\"treeIMG\" src=\"" + imageList.Images[node.imageIndex] + "\"></td>";
	HTML += "<td class=\"treeTD\" id=\"" + node.treeView.name + "_" + node.key + "\" width=\"*\"><nobr>&nbsp<a class=\"treeA\" id=\"treeNode_" + node.key +"\" href=\"javascript:try{var node=" + node.treeView.name + ".Item('" + node.key + "');node.Click();}catch(exp){}\">" + node.text + "</a></nobr></td>";
	HTML += "</tr></table></td></tr>";
	
	return HTML;
}

function CTreeView_HTML()
{
	JSTreeView_continuousImages = "";
	if(this.Nodes.Count()>0)
	{
		var HTML = new String("<table width=\"100%\" cellpadding=0 cellspacing=0>");
		for(var i=0;i<this.Nodes.Count();i++)
		{
			HTML += CTreeView_RecurseForHTML(this.Nodes.l_nodes[i], 0, this.imageList);
		}
		HTML += "</table>";
		return HTML;
	}
	else
	{
		return String("");
	}
}

function CTreeView_RecurseForHTML(node, depth, imageList)
{
	var HTML = new String(CTreeView_CreateNodeHTML(node, depth, imageList));
	if(depth==0) JSTreeView_continuousImages=""; else JSTreeView_continuousImages = JSTreeView_continuousImages.substr(0, depth)
	if(node.nextSibling != null) JSTreeView_continuousImages += "I"; else JSTreeView_continuousImages += "O";
	if(node.isExpanded)
	{
		for(var nodeIndex=0;nodeIndex < node.Nodes.Count(); nodeIndex++)
		{
			HTML += CTreeView_RecurseForHTML(node.Nodes.l_nodes[nodeIndex], depth+1, imageList)
		}
	}
	if(node.IsDraggable) JSTreeView_DraggableNodes.Add(node);
	return HTML;
}

/*
function CTreeView_XML()
{
	if(this.Nodes.Count()>0)
	{
		var XML = new String("<?xml version='1.0'?><treeView name=\"" + this.name + "\" defaultImageFolder=\"" + this.defaultImageFolder + "\" containerElementID=\"" + this.containerElementID + "\">");
		for(var i=0;i<this.Nodes.Count();i++)
		{
			XML += CTreeView_RecurseForXML(this.Nodes.l_nodes[i]);
		}
		XML += "</treeView>";
		return XML;
	}
	else
	{
		return String("<?xml version='1.0'?><treeView />");
	}
}

function CTreeView_RecurseForXML(node)
{
	var XML = new String("<node key=\"" + node.key + "\" text=\"" + node.text + "\" data=\"" + node.data + "\" image=\"" + node.imageIndex + "\"");
	if(node.isChecked) XML += " isChecked=\"1\">"; else XML += " isChecked=\"0\">";
	if(node.Nodes.Count()<=0)
	{
		XML += "<nodes/>";
	}
	else
	{
		XML += "<nodes>";
		for(var nodeIndex=0;nodeIndex < node.Nodes.Count(); nodeIndex++)
		{
			XML += CTreeView_RecurseForXML(node.Nodes.l_nodes[nodeIndex])
		}
		XML += "</nodes>";
	}
	XML += "</node>";
	return XML;
}
*/

function CTreeView_Item(key)
{
	for(var nodeIndex = 0; nodeIndex < this.nodeKeys.length; nodeIndex++)
	{
		if(this.nodeKeys[nodeIndex] == key)
		{
			return this.nodeObjects[nodeIndex];
		}
	}
	return null;
}

function CTreeView_Exists(key)
{
	return this.Item(key) != null;
}

function CTreeView_Add(parentNodeKey, nodeKey, nodeText, nodeURL, nodeImageIndex, isDraggable)
{
	var newNode;
	if(parentNodeKey.length==0)
	{
		newNode = this.Nodes.Add(nodeKey, nodeText, nodeURL, nodeImageIndex, isDraggable);
	}
	else
	{
		var tempNode = this.Item(parentNodeKey);
		if(tempNode==null)
		{
			throw new Error("Parent Node doesn't exists: " + nodeKey, "Parent Node doesn't exists: " + nodeKey);
		}
		newNode = tempNode.Nodes.Add(nodeKey, nodeText, nodeURL, nodeImageIndex, isDraggable);
		tempNode = null;
	}
	this.Refresh();
	return newNode;
}

function CTreeView_Remove(key)
{
	for(var nodeIndex = 0; nodeIndex < this.nodeKeys.length; nodeIndex++)
	{
		if(this.nodeKeys[nodeIndex] == key)
		{
			this.nodeObjects[nodeIndex].Nodes.Clear();
			var nodeArray = this.nodeCollections[nodeIndex].l_nodes;
			for(var nodeInCollection = 0; nodeInCollection < nodeArray.length; nodeInCollection++)
			{
				if(nodeArray[nodeInCollection].key==key)
				{
					nodeArray.splice(nodeInCollection, 1);
					break;
				}
			}
			this.nodeKeys.splice(nodeIndex, 1);
			this.nodeObjects.splice(nodeIndex, 1);
			this.nodeCollections.splice(nodeIndex, 1);
			this.Refresh();
			return true;
		}
	}
	return false;
}

function CTreeView_Refresh()
{
	if(this.isInRunTimeMode)
	{
		JSTreeView_DraggableNodes.Clear();
		
		document.getElementById(this.containerElementID).innerHTML = this.HTML();
		
		if(this.DragDropManager && JSTreeView_DraggableNodes.length > 0)
		{
		    this.DragDropManager.UnregisterAllSourceObjects();
		    for(var i=0;i<JSTreeView_DraggableNodes.length;i++)
		    {
		        var node = JSTreeView_DraggableNodes[i];
		        var obj = document.getElementById(this.name + "_" + node.key);
		        if (obj!=null)
		        {
                    obj.Tag = node;
                    this.DragDropManager.RegisterSourceObject(obj);
                }
		    }
		}
		if(this.selectedNode != null)
		{
			try{document.getElementById(this.name + "_" + this.selectedNode.key).style.fontWeight='bold';}catch(exp){}
		}
	}
}



function CTreeView_SwitchStatus(treeView, nodeKey)
{
	var node = treeView.Item(nodeKey);
	if(node!=null)
	{
		if(node.isExpanded) node.Collapse(); else node.Expand();
	}
}

function CTreeView_SwitchCheckStatus(treeView, nodeKey)
{
	//throw new Error("debug me", "debug me");
	var node = treeView.Item(nodeKey);
	if(node!=null)
	{
		// try calling the check switch delegate for this instance of tree view
		try
		{
			if(treeView.BeforeNodeCheckSwitch != null)
			{
			   treeView.BeforeNodeCheckSwitch(treeView.Item(node));
			}
		}
		catch(exp)
		{
			alert(exp.message);
		}
		if((node.Nodes.Count() > 0) && treeView.checkAffectsChildren)
		{
			CTreeView_RecurseForCheck(node, !node.isChecked);
			treeView.Refresh();
		}
		else
		{
			node.isChecked = !node.isChecked;
			if(node.isChecked)
				document.getElementById("CHK_" + treeView.name + "_" + node.key).src = treeView.defaultImageFolder + "/cbs.gif";
			else
				document.getElementById("CHK_" + treeView.name + "_" + node.key).src = treeView.defaultImageFolder + "/cbns.gif";
		}
	}
}

function CTreeView_RecurseForCheck(node, checkStatus)
{
	node.isChecked = checkStatus;
	for(var nodeIndex = 0; nodeIndex < node.Nodes.Count(); nodeIndex++)
	{
		CTreeView_RecurseForCheck(node.Nodes.l_nodes[nodeIndex], checkStatus);
	}
}

/*****************************************************************************
*                         CTreeViewNodes Procedures                          *
******************************************************************************/

function CTreeViewNodes_Add(nodeKey, nodeText, nodeURL, nodeImageIndex, isDraggable)
{

	if(this.treeView.Exists(nodeKey))
	{
		throw new Error("Node already exists: " + nodeKey, "Node already exists: " + nodeKey);
	}

	var newNode = new CTreeNode(nodeKey, nodeText, nodeURL, nodeImageIndex, this.treeView, isDraggable);

	this.l_nodes.push(newNode);
	this.treeView.nodeKeys.push(nodeKey);
	this.treeView.nodeObjects.push(newNode);
	this.treeView.nodeCollections.push(this);

	if(this.l_nodes.length>1)
	{
		newNode.previousSibling = this.l_nodes[this.l_nodes.length-2];
		newNode.previousSibling.nextSibling = newNode
	}
	return newNode;
	this.treeView.Refresh();
}

function CTreeViewNodes_Clear()
{
	var nodeArray = new Array();
	for(var nodeIndex = 0; nodeIndex < this.l_nodes.length; nodeIndex++)
	{
		nodeArray.push(this.l_nodes[nodeIndex].key);
	}
	for(var nodeIndex = 0; nodeIndex < nodeArray.length; nodeIndex++)
	{
		this.treeView.Remove(nodeArray[nodeIndex]);
	}
	this.treeView.Refresh();
}

function CTreeViewNodes_Count()
{
	return this.l_nodes.length;
}

/*****************************************************************************
*                            CTreeNode Procedures                            *
******************************************************************************/

function CTreeNode_Expand()
{
    
    if (this.treeView.BeforeNodeExpand != null)
    {
        this.treeView.BeforeNodeExpand(this.treeView.Item(this.key));
    }
	/*try
	{
		eval(String(this.treeView.name + "_beforeNodeExpand(this.treeView.Item(\"" + this.key + "\"));"));
	}
	catch(exp)
	{
	}*/
	this.isExpanded = true;
	this.treeView.Refresh();
}
function CTreeNode_Collapse()
{
    if (this.treeView.BeforeNodeCollapse != null)
    {
        this.treeView.BeforeNodeCollapse(this.treeView.Item(this.key));
    }	
//	try
//	{
//		eval(String(this.treeView.name + "_beforeNodeCollapse(this.treeView.Item(\"" + this.key + "\"));"));
//	}
//	catch(exp)
//	{
//	    
//	}
	this.isExpanded = false;
	this.treeView.Refresh();
}

function CTreeNode_Click()
{
	if(this.treeView.selectedNode != null)
	{
		try{document.getElementById(this.treeView.name + "_" + this.treeView.selectedNode.key).style.fontWeight='normal';}catch(exp){}
	}
	this.treeView.selectedNode = this;
	document.getElementById(this.treeView.name + "_" + this.key).style.fontWeight='bold';
	
	if(this.treeView.NodeClick != null)
	{
	    this.treeView.NodeClick(this);
	}
}



/*****************************************************************************
*                            CImageList Procedures                           *
******************************************************************************/

function CImageList_Add(url)
{
    if(url && url.length > 0) window.setTimeout("var img = new Image();img.src = '" + url + "';", 100);
	this.Images.push(url);
}


/*****************************************************************************
*                               Ajax Procedures                              *
******************************************************************************/

var sfcmsAjax = 
{
    Constants :
    {
	    ReadyState:
	    {
		    Uninitialized: 0,
		    Loading: 1,
		    Loaded: 2,
		    Interactive: 3,
		    Complete: 4
	    },
    		
	    Status:
	    {
		    OK: 200,
    		
		    Created: 201,
		    Accepted: 202,
		    NoContent: 204,
    		
		    BadRequest: 400,
		    Forbidden: 403,
		    NotFound: 404,
		    Gone: 410,
    		
		    ServerError: 500
	    },
    		
	    Method:
	    {
	        Get: "GET",
	        Post: "POST"
	    },
    	
	    IEHttpObject: "Microsoft.XMLHTTP"
    },

    IsIE : window.ActiveXObject ? true : false,
    
    ServerRequest: null,

    CallBack : function()
    {
        if (sfcmsAjax.ServerRequest.readyState == sfcmsAjax.Constants.ReadyState.Complete) {
            if (sfcmsAjax.ServerRequest.status == sfcmsAjax.Constants.Status.OK)
            {
                // alert(sfcmsAjax.ServerRequest.responseText);
                eval(sfcmsAjax.ServerRequest.responseText);
            }
            else
            {
                alert("There was a problem retrieving the Server data:\n" + sfcmsAjax.ServerRequest.statusText);
            }
        }        
    },

    Request :
    {
        Prepare: function(data, mthd)
        {
            var queryString = "";
            for(i=0;i<data.length;i+=2)
            {
                queryString += data[i] + "=" + data[i+1] + "&";
            }
            return queryString;
        },
        
        Execute: function(url, mthd, data, async)
        {
            if (!sfcmsAjax.IsIE) sfcmsAjax.ServerRequest = new XMLHttpRequest(); else sfcmsAjax.ServerRequest = new ActiveXObject(sfcmsAjax.Constants.IEHttpObject);
            
            if (sfcmsAjax.ServerRequest)
            {
                sfcmsAjax.ServerRequest.onreadystatechange = sfcmsAjax.CallBack;

                url += "?rnd=" + Math.random() + "&";

                if(mthd == sfcmsAjax.Constants.Method.Get) if(data) if(data.length > 0)
                {
                    url += ServerRequest.PrepareRequest(data, mthd);
                }
                
                var useAsync = async == false ? false : true;
                
                sfcmsAjax.ServerRequest.open(mthd, url, useAsync);
                
                if(mthd == sfcmsAjax.Constants.Method.Post)
                {
                    sfcmsAjax.ServerRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    sfcmsAjax.ServerRequest.send(sfcmsAjax.Request.Prepare(data));
                }
                else
                {
                    sfcmsAjax.ServerRequest.send(null);
                }
                
                if (!sfcmsAjax.IsIE && !useAsync) { sfcmsAjax.CallBack(); }
            }            
        }
    }
}

var sfcms_AJAX_JS_SERVER = "/web/sfcms/sfcms_jsserver.aspx";

function AjaxGetSync(data)
{
    sfcmsAjax.Request.Execute(sfcms_AJAX_JS_SERVER, sfcmsAjax.Constants.Method.Get, data, false);
}

function AjaxGetAsync(data)
{
    sfcmsAjax.Request.Execute(sfcms_AJAX_JS_SERVER, sfcmsAjax.Constants.Method.Get, data, true);
}

function AjaxPostSync(data)
{
    sfcmsAjax.Request.Execute(sfcms_AJAX_JS_SERVER, sfcmsAjax.Constants.Method.Post, data, false);
}

function AjaxPostAsync(data)
{
    sfcmsAjax.Request.Execute(sfcms_AJAX_JS_SERVER, sfcmsAjax.Constants.Method.Post, data, true);
}
